python3_函数式编程

map|reduce|偏函数|装饰器|

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/usr/bin/python3
# -*- coding: utf-8 -*-

print("高阶函数(以函数作为参数)-------------")
def add(x,y,f):
return f(x)+f(y)

print(add(5,-6,abs))

print("map/reduce-------------")
def normalize(name):
return name.capitalize()

L1 = ['adam', 'LISA', 'barT']
print(list(map(normalize, L1)))

print("map/reduce-------------")
from functools import reduce
def multi(x,y):
return x*y

def addone(x):
return x+1
#map(f,[1,2,3]) 对列表每个成员执行操作f
#reduce(f,[1,2,3]) f(f(1,2),3) 依次计算
print(reduce(multi,map(addone,[1,2,3,1,1,1])))

print("filter-------------")
# filter(f,[1,2,3]) 对列表每一项进行f函数,如果结果为true则保留该值
# list(filter(f,[1,2,3])) 由于filter是惰性求值,需要list才能获得整个列表
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
def _not_divisible(n):
return lambda x: x % n > 0
#埃氏筛法
def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一个数
yield n
it = filter(_not_divisible(n), it) # 构造新序列
# 打印1000以内的素数:
for n in primes():
if n < 2:
print(n)
else:
break

print("sorted-------------")
#sorted 是python内置排序算法,可以额外接受一个函数
#内部比较两个元素时,按照分别给两个元素执行函数后的结果进行比较
sorted([36, 5, -12, 9, -21], key=abs)

print("闭包-------------")
#要记得_sum()中不应当引用会变化的变量
def sum(a,b):
x=1
def _sum():
return (a+x)*(b+x)
return _sum
f=sum(1,1)
print(f())

print("lambda-------------")
f=lambda x:x*x
print(f(2))
print(list(map(lambda x:x*x*x,[1,2,3])))

print("装饰器-------------")

def log(func):
def wrapper(*args,**kw):
print('call %s' % func.__name__)
return func(*args,**kw)
return wrapper

@log
def now():
print('20191111')

now()

print("偏函数-------------")
print(int('100101001',base=2))
import functools
int2=functools.partial(int,base=2)
print(int2("10001"))
#模块的目录
import sys
print(sys.path)

print("private函数-------------")
def _hello():
print("hello")
def hello():
_hello()
hello()

'''
print("pillow库测试-------------")
from PIL import ImageFilter
from PIL import Image

imgF = Image.open("./test.jpg")
outF = imgF.filter(ImageFilter.DETAIL)
conF = imgF.filter(ImageFilter.CONTOUR)
edgeF = imgF.filter(ImageFilter.FIND_EDGES)
imgF.show()
outF.show()
conF.show()
edgeF.show()

参考

欢迎与我分享你的看法。
转载请注明出处:http://taowusheng.cn/